package com.spark.colliery

import android.annotation.SuppressLint
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.view.WindowManager
import android.widget.Toast
import com.spark.common.BaseActivity

class MainActivity : BaseActivity() {

    companion object {
        const val killselfAction = "com.spark.colliery.KILL_SELF"
        fun actionStart(host: Activity) {
            val intent = Intent(host, MainActivity::class.java)
            host.startActivity(intent)
        }
    }

    private lateinit var exitToast: Toast
    private var killselfBC: KillselfBC? = null

    private var last: Long = 0
    private var interval: Long = 2000

    override fun contentResId(): Int {
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        return R.layout.act_main_container
    }

    @SuppressLint("ShowToast")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (findFragment(MainFragment::class.java) == null)
            loadRootFragment(R.id.fl_container, MainFragment.newInstance())
        exitToast = Toast.makeText(this, "再点一次退出应用程序", Toast.LENGTH_SHORT)

        killselfBC = KillselfBC(this)
        val iff = IntentFilter().apply {
            priority = IntentFilter.SYSTEM_HIGH_PRIORITY
            addAction(MainActivity.killselfAction)
        }
        killselfBC?.apply {
            LocalBroadcastManager.getInstance(this@MainActivity).registerReceiver(this, iff)
        }
    }

    override fun onDestroy() {
        killselfBC?.apply {
            LocalBroadcastManager.getInstance(this@MainActivity).unregisterReceiver(this)
        }
        super.onDestroy()
    }

    override fun onBackPressedSupport() {
        if (fragmentManager.backStackEntryCount > 1 || supportFragmentManager.backStackEntryCount > 1)
            super.onBackPressedSupport()
        else {
            val fragment = this.topFragment
            if (fragment !is MainFragment || !fragment.canGoback()) {
                val cur = System.currentTimeMillis()
                if (cur - last < interval) {
                    finish()
                    exitToast.cancel()
                } else {
                    exitToast.show()
                }
                last = cur
            }
        }

    }

}

class KillselfBC(var act: Activity) : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.apply {
            if (MainActivity.killselfAction == action) {
                act.finish()
            }
        }
    }
}